package com.lgb.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
//拦截含有Controller注解的类
public class ControllerExceptionHandler {

    //获取日志对象
    private Logger logger = LoggerFactory.getLogger((this.getClass()));

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request ,Exception e) throws Exception {
        //输出错误信息
        logger.error("Reqquest URL: {} , Exception : {}",request.getRequestURI(),e);

        //如果类含有ResponseStatus注释，则抛出异常，交由SpringBoot处理
        if(AnnotationUtils.findAnnotation(e.getClass() , ResponseStatus.class) != null){
            throw e;
        }

        ModelAndView modelAndView = new ModelAndView();
        //获取url
        modelAndView.addObject("url",request.getRequestURI());
        //获取异常信息
        modelAndView.addObject("exception",e);
        //返回页面 error目录下的error.html
        modelAndView.setViewName("error/error");
        //返回modelandview
        return modelAndView;
    }
}
